﻿#include "libge2d_extension.h"
#include "SDL.h"
#include "klbmem/klb_mem.h"
#include "core/klbge2d.h"
#include <assert.h>


#define LIBGE2D_EXTENSION      "LIBGE2D_EXTENSION"


typedef struct libge2d_extension_t_
{
    klua_env_t*         p_env;              ///< 附加环境: env

    klbge2d_t*          p_ge2d;             ///< game engine 2D
}libge2d_extension_t;


//////////////////////////////////////////////////////////////////////////

void* libge2d_extension_create(klua_env_t* p_env)
{
    libge2d_extension_t* p_ex = KLB_MALLOCZ(libge2d_extension_t, 1, 0);

    p_ex->p_env = p_env;

    p_ex->p_ge2d = klbge2d_create();

    return p_ex;
}

void libge2d_extension_destroy(void* ptr)
{
    libge2d_extension_t* p_ex = (libge2d_extension_t*)ptr;

    // 退出
    klbge2d_quit(p_ex->p_ge2d);

    // 销毁
    KLB_FREE_BY(p_ex->p_ge2d, klbge2d_destroy);
    KLB_FREE(p_ex);
}

int libge2d_extension_loop_once(void* ptr, klua_env_t* p_env, int64_t last_tc, int64_t now)
{
    libge2d_extension_t* p_ex = (libge2d_extension_t*)ptr;

    if (0 != klbge2d_loop_once(p_ex->p_ge2d, last_tc, now))
    {
        klua_env_exit(p_ex->p_env);
    }

    return 0;
}

//////////////////////////////////////////////////////////////////////////
// 导出

int libge2d_extension_init(libge2d_extension_t* p_ex, int w, int h, const char* p_title)
{
    return klbge2d_init(p_ex->p_ge2d, w, h, p_title);
}

void libge2d_extension_quit(libge2d_extension_t* p_ex)
{
    klbge2d_quit(p_ex->p_ge2d);
}

klbge2d_t* libge2d_extension_get(libge2d_extension_t* p_ex)
{
    return p_ex->p_ge2d;
}

//////////////////////////////////////////////////////////////////////////

int kluaex_register_libge2d(klua_env_t* p_env)
{
    // 注册 lua env 扩展
    klua_env_extension_t ex = { 0 };

    ex.cb_create = libge2d_extension_create;
    ex.cb_destroy = libge2d_extension_destroy;
    ex.cb_loop_once = libge2d_extension_loop_once;

    klua_env_register_extension(p_env, LIBGE2D_EXTENSION, &ex);

    return 0;
}

libge2d_extension_t* kluaex_get_libge2d(klua_env_t* p_env)
{
    libge2d_extension_t* p_ex = (libge2d_extension_t*)klua_env_get_extension(p_env, LIBGE2D_EXTENSION);
    if (NULL == p_ex)
    {
        kluaex_register_libge2d(p_env);
        p_ex = (libge2d_extension_t*)klua_env_get_extension(p_env, LIBGE2D_EXTENSION);
    }

    return p_ex;
}

libge2d_extension_t* kluaex_get_libge2d_by_L(lua_State* L)
{
    return kluaex_get_libge2d(klua_env_get_by_L(L));
}
